import os
from flask import Flask, jsonify
from flask_sqlalchemy import SQLAlchemy
from flask_jwt_extended import JWTManager
from flask_cors import CORS

# 创建Flask应用实例
app = Flask(__name__)

# 添加CORS支持
CORS(app, resources={r"/api/*": {"origins": "*"}})

# 配置数据库URI连接到远程MySQL数据库
app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql+mysqlconnector://user:password@ip:port/erp_db'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
app.config['SQLALCHEMY_ENGINE_OPTIONS'] = {
    'pool_recycle': 300,
    'pool_pre_ping': True
}

# JWT配置
app.config['JWT_SECRET_KEY'] = 'erp-system-secret-key-change-in-production'
app.config['JWT_ACCESS_TOKEN_EXPIRES'] = 3600  # 1小时过期
app.config['JWT_TOKEN_LOCATION'] = ['headers']
app.config['JWT_HEADER_NAME'] = 'Authorization'
app.config['JWT_HEADER_TYPE'] = 'Bearer'

jwt = JWTManager(app)

# 初始化数据库
db = SQLAlchemy(app)

# 导入模型（需要在db初始化之后）
from models import User, AccountingSubject, Voucher, VoucherEntry, Product, Bom, ProductionOrder, Supplier, PurchaseOrder, PurchaseOrderItem, Employee, Payroll, Attendance

# 导入路由
from routes import auth_bp, finance_bp, production_bp, supplychain_bp, hr_bp

# 注册蓝图
app.register_blueprint(auth_bp)
app.register_blueprint(finance_bp)
app.register_blueprint(production_bp)
app.register_blueprint(supplychain_bp)
app.register_blueprint(hr_bp)

@app.before_first_request
def create_tables():
    db.create_all()

# JWT错误处理
@jwt.expired_token_loader
def expired_token_callback(jwt_header, jwt_payload):
    print(f"令牌已过期: header={jwt_header}, payload={jwt_payload}")
    return jsonify({
        'code': 401,
        'message': '令牌已过期',
        'data': None
    }), 401

@jwt.invalid_token_loader
def invalid_token_callback(error):
    print(f"无效的令牌: {error}")
    return jsonify({
        'code': 401,
        'message': '无效的令牌',
        'data': None
    }), 401

@jwt.unauthorized_loader
def missing_token_callback(error):
    print(f"缺少访问令牌: {error}")
    return jsonify({
        'code': 401,
        'message': '缺少访问令牌',
        'data': None
    }), 401

# 添加用户查找回调
@jwt.user_lookup_loader
def user_lookup_callback(_jwt_header, jwt_data):
    identity = jwt_data["sub"]
    print(f"查找用户: identity={identity}, type={type(identity)}")
    if isinstance(identity, str):
        user = User.query.get(int(identity))
    else:
        user = User.query.get(identity)
    print(f"找到用户: {user}")
    return user

if __name__ == '__main__':
    app.run(debug=True, host='127.0.0.1', port=5000)